﻿
(function ($) {
    var status = {
        wait: 0,
        uploading: 1,
        stop: 2,
        finish: 3
    }

    var File = function (file) {
        this.ATTACHMENT_ID = '';
        this.ATTACHMENT_NAME = escape(file.name);
        this.ATTACHMENT_SIZE = file.size;
        this.FILE_RELATIVE_PATH = ''
        this.Status = status.wait;
        this.Token = $.cookie("TokenGuid");
        this.CurrentPosition = 0;
    }

    var s;
    var Attachment = function ($this, parm) {
        this.$this = $this;
        parm.Attachment = this;
        this.parm = parm;
        this.fileList = [];
        if (parm.ObjectId && parm.SimpleModel) {
            this.LoadSimple();
        } else {
            this.Init();
        }

    }

    Attachment.prototype = {
        LoadSimple: function () {
            var me = this;
            $.AjaxRequest('L_GetAttachmentByObjId', me.parm.ObjectId, function (files) {
                $.each(files, function (i, file) {
                    var f = {};
                    f.dto = file;
                    f.name = file.ATTACHMENT_NAME;
                    f.size = file.ATTACHMENT_SIZE;
                    me.LoadfileSimple(f);
                });
                if (me.parm.AfterLoad)
                    me.parm.AfterLoad(files);
            });


        },
        /*参数说明*/
        DefaultParm: {
            //上传文件快大小 默认512kb
            blocksize: 1024 * 512,
            //文件最大大小（单位btyte） 默认最大20mb
            MaxSize: false,// 1024 * 1024 * 20,
            //用于获得附件的业务主键
            ObjectId: undefined,
            //是否显示上传按钮
            CanUpLoad: true,
            //业务保存按钮
            SubmitBtn: undefined,
            //加载完成后执行的事件
            AfterLoad: function () { },
            //上传路径
            Catalog: '/upload/file',
            //是否可以预览
            CanView: false,
            //是否可以删除附件
            CanDelete: true,
            //业务表名
            TableName: ''
        },

        LoadfileSimple: function (file) {
            var me = this;
            var i_html = $("<i style='display:inline-block;'>");
            var type = file.dto.ATTACHMENT_TYPE.toLowerCase();
            switch (type) {
                case 'xls':
                    i_html.addClass('excel');
                    break;
                case 'xlsx':
                    i_html.addClass('excel');
                    break;
                case 'doc':
                    i_html.addClass('word');
                    break;
                case 'docx':
                    i_html.addClass('word');
                    break;
                case 'pdf':
                    i_html.addClass('pdf');
                    break;
                case 'jepg':
                    i_html.addClass('img');
                    break;
                case 'jpg':
                    i_html.addClass('img');
                    break;
                case 'bmp':
                    i_html.addClass('img');
                    break;
                case 'gif':
                    i_html.addClass('img');
                    break;
                case 'png':
                    i_html.addClass('img');
                    break;
                default:
                    i_html.addClass('other');
                    break;
            }          
            var aFile = $("<a class='fileName simple' style='display:inline-block; max-width:300px;'>").append(i_html).append($("<span>").html(file.name)).attr('download', file.dto.ATTACHMENT_NAME)
                .css({
                    'white-space': 'nowrap',
                    'word-break': 'keep-all',
                    'overflow': 'hidden',
                    'text-overflow': 'ellipsis'
                }).attr('title', file.dto.ATTACHMENT_NAME);
            aFile.click(function () {               
                me.DownLoad(file);               
            });

            me.$this.append(aFile);
        },

        Init: function () {
            var me = this;
            this.uploadCount = 0;

            for (i in me.DefaultParm) {
                if (me.parm[i] == undefined) {
                    me.parm[i] = me.DefaultParm[i];
                }
            }

            this.view = $("<div class='attachment-view attachment-view-displaynone'>");
            this.view_container = $("<div>");
            this.closeView = $("<div  class='img-close' ><i></i></div>");


            this.view_content = $("<div class='view-content'>");
            this.view.append(this.view_container.append(this.closeView).append(this.view_content));

            $("body").append(this.view);
            this.content = $("<div class='attachment-content'>");
            this.upload = $("<div class='upload display-none'>")
            this.$this.addClass('attachment');

            this.divBtn = $("<div  class='sl_container display-none' ><div><span>上传附件</span><input type='file' style='opacity:0'   multiple/></div></div>");
            this.$this.append(this.divBtn);

            this.btn = this.divBtn.find("input");

            this.closeView.click(function () {
                me.view.addClass("attachment-view-displaynone");
            })

            function getstyle() {
                if ($.cookie('current-skin'))
                    return $.cookie('current-skin').replace('/assets/css/skins/', '').replace('.min.css', '');
                return null;
            }

            var rel = getstyle();

            rel = rel ? 'bordered-' + rel : 'bordered-darkorange';
            if (me.parm.CanUpLoad) {
                this.$this.append(this.upload.append($("<div class='title " + rel + " '><div  class='fileName'>文件名</div><div class='fileSize'>大小</div><div  class='filespeed'>速度</div><div  class='operate'>操作</div></div>")).append(this.content));
            }
            else {
                this.$this.append(this.upload.append($("<div class='title " + rel + " '><div  class='fileName'>文件名</div><div class='fileSize' style='width:30%'>大小</div><div  style='width:20%' class='operate'>操作</div></div>")).append(this.content));
            }
            var fileList = $("<div class='upload'> </div>");
            if (me.parm.SubmitBtn) {
                me.parm.SubmitBtn.on('canSubmit', function (obj, handler, hander2) { return me.IsFinish($(this), handler, hander2); })
                  .on('attachment', function (obj, objIds) {
                      me.SaveAttachmentMapping(objIds);
                  }).on('canupload', function () {
                      me.CanUpload();
                  }).on('reset', function () { me.Reset(); });
            }
            if (me.parm.ObjectId) {
                $.AjaxRequest('L_GetAttachmentByObjId', me.parm.ObjectId, function (files) {
                    $.each(files, function (i, file) {
                        var f = {};
                        f.dto = file;
                        f.name = file.ATTACHMENT_NAME;
                        f.size = file.ATTACHMENT_SIZE;
                        me.Loadfile(f);
                    });
                    if (me.parm.AfterLoad) { me.parm.AfterLoad(files); }
                });
            }

            if (me.parm.CanUpLoad) { me.CanUpload(); }
        },

        DownLoad: function (file) {
            var form = $("<form method='post' action='/handlers/do.ashx' style='display:none'>");
            $("body").append(form);
            var input = $("<input>").attr('name', 'RequestData').val($.toJSON({ TokenGuid: $.token(), ActionCode: 'L_DownLoadAttachment', Data: $.toJSON({ ATTACHMENT_ID: file.dto.ATTACHMENT_ID }) }));
            form.append(input);
            form.submit();
        },

        Reset: function () {
            var me = this;
            me.content.html('');
            me.fileList = [];
            me.upload.addClass('display-none');

        },

        ResetSubmitBtn: function (submitBtn) {
            var me = this;
            if (me.parm.SubmitBtn) {
                me.parm.SubmitBtn.unbind();
            }
            me.parm.SubmitBtn = submitBtn;

            me.parm.SubmitBtn.on('canSubmit', function (obj, handler, hander2) { return me.IsFinish($(this), handler, hander2); })
              .on('attachment', function (obj, objId) { me.SaveAttachmentMapping(objId); })
          .on('canupload', function () {
              me.CanUpload();
          }).on('reset', function () { me.Reset(); });
        },

        CanUpload: function () {
            var me = this;

            me.divBtn.removeClass("display-none");
            me.btn.unbind();
            me.$this.unbind();
            me.btn.change(function (e) {

                if (this.files)
                    me.StartUpload(this.files);
                $(this).val('');
            })

            me.$this.attr('draggable', 'true').on({
                'dragenter': function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                }, 'dragover': function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                }, 'drop': function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                    var dt = e.originalEvent.dataTransfer;
                    me.StartUpload(dt.files);
                }
            });
        },


        StartUpload: function (files) {
            var me = this;
            if (files.length && me.parm.MaxSize) {
                var canNotUpload = [];
                $.each(files, function (a, file) {
                    if (file.size > me.parm.MaxSize)
                        canNotUpload.push(file);
                });
                if (canNotUpload.length > 0) {
                    var message = $.format('以下文件大小超出限制，最大上传 {0} 的文件\r\n', me.GetFileSize(me.parm.MaxSize));
                    $.each(canNotUpload, function (i, val) {
                        message += $.format('    {0}\r\n', val.name);
                    });
                    message += "";
                    alert(message);
                    return;
                }
            }


            if (files.length) {
                $.each(files, function (a, file) {
                    me.Addfile(file);
                })

            }
        },

        Loadfile: function (file) {
            var me = this;
            // if (this.divBtn)
            //this.divBtn.removeClass('center');
            this.upload.removeClass('display-none');
            //需要验证是否存在这个文件
            this.fileList.push(file);
            var div = $("<div class='upload'>");
            file.divcontainer = $("<div class='file-progress '>");
            file.fileprogress = $("<div class='divProgress display-none'>");
            var filename = $("<div class='fileName'>");//

            var i_html = $("<i>");
            var afile = me.parm.CanView ? $("<a>").append(i_html).append($("<span>").html(file.name)) : $("<span>").append(i_html).append($("<span>").html(file.name));
            var type =file.dto.ATTACHMENT_TYPE? file.dto.ATTACHMENT_TYPE.toLowerCase():'';
            switch (type) {
                case 'xls':
                    i_html.addClass('excel');
                    break;
                case 'xlsx':
                    i_html.addClass('excel');
                    break;
                case 'doc':
                    i_html.addClass('word');
                    break;
                case 'docx':
                    i_html.addClass('word');
                    break;
                case 'pdf':
                    i_html.addClass('pdf');
                    break;
                case 'jepg':
                    i_html.addClass('img');
                    break;
                case 'jpg':
                    i_html.addClass('img');
                    break;
                case 'bmp':
                    i_html.addClass('img');
                    break;
                case 'gif':
                    i_html.addClass('img');
                    break;
                case 'png':
                    i_html.addClass('img');
                    break;
                default:
                    i_html.addClass('other');

                    break;
            }

            filename.append(afile);

            if (me.parm.CanView) {
                afile.click(function () {
                    me.view_content.html('');


                    var position = file.dto.FILE_NETWORK_PATH.lastIndexOf(".");
                    var length = file.dto.FILE_NETWORK_PATH.length;
                    var fileType = file.dto.FILE_NETWORK_PATH.substring(position, length - position).toLowerCase();



                    if (type == 'xls' || type == 'doc' || type == "ppt" || type == "xlsx" || type == "docx" || type == "pptx") {
                        var path = file.dto.FILE_NETWORK_PATH.substring(0, position) + ".pdf";
                        var iframe = $("<iframe>").attr('src', '/Packages/PanManagement/Resources/FlexPaper_Zine_Trial/browse.html?FilePath=' + escape(path));
                        me.view_content.append(iframe);
                    }
                    else if (type == "jepg" || type == "jpg" || type == "bmp" || type == "gif" || type == "png") {
                        var img = $("<img>").attr('src', file.dto.FILE_NETWORK_PATH);

                        me.view_content.append(img);


                    }
                    me.view.removeClass("attachment-view-displaynone");

                });

            }
            else {


            }
            var filesize = $("<div class='fileSize'>").html(me.GetFileSize(file.size));

            //操作区
            file.operate = $("<div class='operate'>");

            me.content.append(file.divcontainer.append(file.fileprogress).append(filename).append(filesize));
            if (me.parm.CanUpLoad) {
                file.filespeed = $("<div class='filespeed'>").html(0);
                file.divcontainer.append(file.filespeed)
            }
            else {
                filesize.css('width', '30%');
                file.operate.css('width', '20%');
            }
            file.divcontainer.append(file.operate);
            //下载
            var down = $("<a ><i  class='glyphicon glyphicon-download-alt'></i>下载</a>").attr('download', file.dto.ATTACHMENT_NAME);
            //.attr('href', file.dto.FILE_NETWORK_PATH)
            //var down = $("<a class='glyphicon glyphicon-download-alt'>")
            file.operate.append(down);
            down.click(function () {
                me.DownLoad(file);

           
            });
            if (me.parm.CanDelete) {
                var colse_btn = $("<a><i class='glyphicon glyphicon-remove'></i>删除</a>");
                file.operate.append(colse_btn);

                colse_btn.click(function () {
                    me.DeleteFile(file);
                });
            }

        },
        DeleteFile: function (file) {
            var me = this;
            if (confirm('确认删除？')) {
                for (i = 0; i < me.fileList.length; i++) {
                    if (me.fileList[i].dto.ATTACHMENT_ID == file.dto.ATTACHMENT_ID) {
                        me.fileList.splice(i, 1);
                        file.divcontainer.remove();
                        break;
                    }
                }
                $.AjaxRequest('System_RemoveAttachment', file.dto.ATTACHMENT_ID, function () { });
                if (me.fileList.length == 0) {
                    me.upload.addClass('display-none');
                }
            }
        },

        Addfile: function (file) {
            var me = this;
            //this.divBtn.removeClass('center');
            this.upload.removeClass('display-none');
            var fileDto = new File(file);
            file.dto = fileDto;
            //需要验证是否存在这个文件
            this.fileList.push(file);
            var div = $("<div class='upload'>");
            file.divcontainer = $("<div class='file-progress '>");
            file.fileprogress = $("<div class='divProgress display-none'>");
            var filename = $("<div class='fileName'>").html(file.name);
            var filesize = $("<div class='fileSize'>").html(me.GetFileSize(file.size));
            file.filespeed = $("<div class='filespeed'>").html(0);
            file.operate = $("<div class='operate'>");
            file.id = '';
            file.currentBlock = 0;
            var colse_btn = $("<a><i class='glyphicon glyphicon-remove'></i>删除</a>");
            file.operate.append(colse_btn);
            me.content.append(file.divcontainer.append(file.fileprogress).append(filename).append(filesize).append(file.filespeed).append(file.operate));
            if (me.uploadCount < 5)
                me.UploadFile(file);
            colse_btn.click(function () {
                me.DeleteFile(file);
            });
        },

        GetFileSize: function (size) {
            if (size < 1024)
                return size.toFixed(2) + "b";
            else if (size >= 1024 && size < 1024 * 1024)
                return (size / 1024).toFixed(2) + "kb";
            else if (size >= 1024 * 1024 && size < 1024 * 1024 * 1024)
                return (size / (1024 * 1024)).toFixed(2) + "mb";
            else return (size / (1024 * 1024 * 1024)).toFixed(2) + "gb";
        },

        UploadFile: function (file) {
            var me = this;
            ++me.uploadCount;
            file.dto.Status = status.uploading;
            file.dto.Catalog = me.parm.Catalog;
            $.AjaxRequest("L_PrepareAddAttachment", file.dto, function (data) {
                file.fileprogress.removeClass('display-none');
                file.dto.FILE_RELATIVE_PATH = data.FILE_RELATIVE_PATH;
                file.dto.ATTACHMENT_ID = data.ATTACHMENT_ID;
                var reader = new FileReader();

                file.dto.CurrentPosition = data.CurrentPosition;
                me.ReadFile(reader, file, data.CurrentPosition, data.CurrentPosition + me.parm.blocksize)
            });
            //file.Status=



        },

        Speed: function (time1, time2) {
            var timespan = (time2 - time1) / 1000;
            return this.GetFileSize(this.parm.blocksize / timespan) + "/s";
        },

        ReadFile: function (reader, file, start, end) {
            var me = this;

            var time1 = new Date();
            if (end > file.size)
                end = file.size;

            var content = file.slice(start, end);
            if (reader.readAsArrayBuffer) {
                reader.readAsArrayBuffer(content);
                //reader.readAsBinaryString(content);
            }
            else {
                reader.readAsBinaryString(content);
            }

            reader.onload = function (e) {

                //function byteValue(x) {
                //    return x.charCodeAt(0) & 0xff;
                //}
                //var ords = Array.prototype.map.call(datastr, byteValue);
                //var ui8a = new Uint8Array(ords);
                //this.send(ui8a.buffer);



                $.ajax({
                    type: "POST",
                    url: '/Handlers/UploadAttachmentHandler.ashx?FILE_RELATIVE_PATH=' + escape(file.dto.FILE_RELATIVE_PATH),
                    dataType: 'text',
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    // data: this.result,
                    data: e.target.result,
                    success: function (data) {

                        file.fileprogress.css('width', (100 * end / file.size) + "%");
                        ++file.currentBlock;
                        if (file.currentBlock % 10 == 1) {
                            var time2 = new Date();
                            file.filespeed.html(me.Speed(time1, time2));
                        }
                        if (end < file.size) {
                            start = end;
                            var result = this.result;

                            window.setTimeout($.proxy(function () {
                                me.ReadFile(reader, file, start, start + me.parm.blocksize)
                            }), 10);

                        }
                        else {

                            $.AjaxRequest("L_AddAttachment", file.dto, function () {
                                file.fileprogress.addClass('display-none');
                                file.filespeed.html('<i></i>');
                                file.dto.Status = status.finish;
                                --me.uploadCount;
                                if (me.uploadCount < 5) {
                                    $.each(me.fileList, function (i, val) {
                                        if (val.dto.Status == status.wait) {
                                            me.UploadFile(val);
                                            return false;
                                        }
                                    })
                                }

                            })

                        }
                    }
                });
            };
        },

        IsFinish: function (btn, handler1, handler2) {
            var me = this;
            var flag = true;
            $.each(me.fileList, function (i, val) {
                if (val.dto.Status < status.finish) {
                    flag = false;
                    return false;
                }
            })
            if (flag && handler1) {
                handler1(me.fileList);
            } else {
                if (handler2)
                    handler2();
                else {

                    alert("正在上传附件，请等待");
                    btn.button('reset');
                }
            }

        },

        SaveAttachmentMapping: function (objId) {
            var me = this;
            var fileList = [];
            function generateParm(id) {
                $.each(me.fileList, function (i, file) {
                    var dto = file.dto;
                    fileList.push({
                        ATTACHMENT_ID: dto.ATTACHMENT_ID,
                        OBJECT_ID: id,
                        OBJECT_TABLE_NAME: me.parm.TableName
                    });
                });

            }
            if (objId instanceof Array) {
                $.each(objId, function (i, id) {
                    generateParm(id);
                })
            } else
                generateParm(objId);

            $.AjaxRequest("L_SaveAttachmentMapping", fileList, function () { }, false);


        }

    }





    //attachment_parm = {
    //    ObjectId: core.INSTANCE_ID,
    //    CanUpLoad: core.CanEdit,
    //    SubmitBtn: asubmit,
    //    TableName: parm.TableName
    //};


    $.fn.attachment = function (parm) {

        new Attachment($(this), parm);

    }
})(jQuery)